<template>
  <el-upload
    class="avatar-uploader"
    v-model:file-list="fileList"
    :action="uploadUrl"
    :data="{
      sign: '1606559655810000',
    }"
    :headers="{
      'Access-Token': userStore.token
    }"
    name="files"
    :show-file-list="false"
    :limit="2"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <el-button type="primary">Click to upload</el-button>
    <template #tip>
      <div class="el-upload__tip">
        {{ fileName }}
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

//接受父组件传递过来的参数
let props = defineProps({
  modelValue: String,
  // 数量
  max: {
    type: [Number, String],
    default: 1,
  },
  // 大小 单位 MB
  size: {
    type: Number,
    default: 10,
  },
})

const fileList = ref([])

const uploadUrl = import.meta.env.VITE_UPLOAD_SERVE
const previewUrl = import.meta.env.VITE_IMG_SERVE
const imageUrl = ref('')
let $emit = defineEmits(['update:modelValue'])

onMounted(() => {
  fileName.value = props.modelValue
})
watch(
  () => props.modelValue,
  (val) => {
    if (!val)
    fileName.value = ''
    else
    fileName.value = val
  },
)
let fileName =ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  let { status, data } = response
  if (status == 200) {
    let urls = data.map((v) => v.fileUrl).join(',')
    let names = data.map((v) => v.fileName).join(',')
    fileName.value = names
    $emit('update:modelValue', urls)
  }
}

const alowTypes = ['image/jpeg', 'image/png', 'image/webp']
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  fileList.value = []
  // if (!alowTypes.includes(rawFile.type)) {
  //   ElMessage.error('请选择 .jpeg .png .webp 格式的文件')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > props.size) {
  //   ElMessage.error(`图片大小不能超过${props.size}MB!`)
  //   return false
  // }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
